package com.crm.consult.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.crm.annotation.SystemServiceLog;
import com.crm.cache.ICache;
import com.crm.cache.MainCacheUtil;
import com.crm.model.BizSysuserCitys;
import com.crm.model.ConsultInfoManage;
import com.crm.model.ConsultInfoManagePay;
import com.crm.model.ConsultInfoManageServer;
import com.crm.model.SysDepartment;
import com.crm.model.SysDuty;
import com.crm.model.SysUser;
import com.crm.model.entity.CountWorkBench;
import com.crm.model.entity.Msg;
import com.crm.service.ConsultInfoManagePayService;
import com.crm.service.ConsultInfoManageServerService;
import com.crm.service.ConsultInfoManageService;
import com.crm.service.SysDepartmentService;
import com.crm.service.SysDutyService;
import com.crm.service.SysUserService;
import com.crm.util.AopConfig;
import com.crm.util.DataUtil;
import com.crm.util.JsonUtil;
import com.crm.util.ResponseUtil;
import com.crm.util.SMSUtil;
import com.crm.util.SessionModel;
import com.crm.util.SessionUtils;

@Controller
@RequestMapping("/consultConsole")
public class ConsultConsoleController {
	
	@Autowired
	private SysDepartmentService sysDepartmentService;
	@Autowired
	private ConsultInfoManageService consultInfoManageService;
	@Autowired
	private ConsultInfoManageServerService consultInfoManageServerService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private ConsultInfoManagePayService consultInfoManagePayService;
	@Autowired
	private MainCacheUtil systemConfigManager;
	@Autowired
	private SysDutyService sysDutyService;

	public void setSystemConfigManager(MainCacheUtil systemConfigManager) {
		this.systemConfigManager = systemConfigManager;
	}

	@RequestMapping("/index")
	public String index(HttpServletRequest request){
		SysUser sy = (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
		if(sy==null){ 
			return "tologin";    
		}
//		SysDepartment sd = sysDepartmentService.selectByPrimaryKey(sy.getCompanyId());
		request.setAttribute("user", sy);
		if(sy!=null){
			if("3".equals(sy.getDepType())){
				List<SysUser> userList = getUsers();
				String ar = "";
				for(SysUser e:userList){
					ar = ar+"'"+e.getUserId()+"',";
				}
				ar = ar+"'"+sy.getUserId()+"'";
				if("1".equals(sy.getSecurityLevel())){
					request.setAttribute("dep", "'"+sy.getUserId()+"'");
				}else{
					request.setAttribute("dep", ar);
				}
				request.setAttribute("type", 3);
				BizSysuserCitys bsc = new BizSysuserCitys();
				bsc.setDepartmentId("'"+sy.getCompanyId()+"'");
				userList.add(sy);
				request.setAttribute("selectList", userList);
			}else if("1".equals(sy.getDepType())){
				request.setAttribute("type", 1);
				List<SysUser> userList = getUsers();
				String ar = "";
				for(SysUser e:userList){
					ar = ar+"'"+e.getUserId()+"',";
				}
				ar = ar+"'"+sy.getUserId()+"'";
				request.setAttribute("dep", ar);
				userList.add(sy);
				request.setAttribute("selectList", userList);
			}
		}else{
			request.setAttribute("dep", sy.getDepartmentId());
		}
		return "consultcenter/consultWorkbench";
	}
	
	/**
	 * 
	 * @Description : 以职位为条件检索出用户群体
	 * @author zealot
	 * @param @return
	 * @return List<SysUser>
	 * @version 创建时间 : 2016年12月20日 下午3:53:56
	 * @thorws
	 */
	public List<SysUser> getUsers(){
		SysUser sy = (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
		return sysUserService.selectByDuty(sy);
	}
	
	/**
	 * 
	 * @Description : 预约单分配
	 * @author zealot
	 * @param @param response
	 * @param @param request
	 * @param @param ar
	 * @param @param reviceName
	 * @param @param reviceId
	 * @return void
	 * @version 创建时间 : 2016年12月6日 下午4:46:32
	 * @thorws
	 */
	@SystemServiceLog(description=AopConfig.CONSULTCONSOLE+AopConfig.ASSIGNED,type=AopConfig.ASSIGNED)
	@RequestMapping("/toChooseAr")
	public void toChooseAr(HttpServletResponse response,HttpServletRequest request,String ar,String reviceName,String reviceId){
		if(ar!=null){
			String[] ary = ar.split(",");
			ConsultInfoManage cim = null;
			for(String e : ary){
				cim = new ConsultInfoManage();
				cim.setReciveId(reviceId);
				cim.setReciveName(reviceName);
				cim.setInfoManageId(e);
				consultInfoManageService.updateByPrimaryKey(cim);
			}
			ResponseUtil.result(response,JsonUtil.toJsonStr("success"));
		}
	}
	
	/**
	 * 
	 * @Description : 上门未报名原因添加
	 * @author zealot
	 * @param @param response
	 * @param @param request
	 * @param @param ar
	 * @param @param reviceName
	 * @param @param reviceId
	 * @return void
	 * @version 创建时间 : 2016年12月6日 下午4:48:17
	 * @thorws
	 */
	@SystemServiceLog(description=AopConfig.DROPFALSE+AopConfig.ADD,type=AopConfig.ADD)
	@RequestMapping("/dropFalse")
	public void dropFalse(HttpServletResponse response,HttpServletRequest request,ConsultInfoManageServer record){
		consultInfoManageServerService.updateByPrimaryKeySelective(record);
		ResponseUtil.result(response,JsonUtil.toJsonStr("success"));
	}
	
	/**
	 * 
	 * @Description : 工作台记录状态
	 * @author zealot
	 * @param @param response
	 * @param @param request
	 * @param @param record
	 * @return void
	 * @version 创建时间 : 2016年12月8日 下午6:39:22
	 * @thorws
	 */
	@SystemServiceLog(description=AopConfig.CONSULTINFOWORKBENCH+AopConfig.ADD,type=AopConfig.ADD)
	@RequestMapping("/recordMsg")
	public void recordMsg(HttpServletResponse response,HttpServletRequest request,ConsultInfoManageServer record){
		consultInfoManageServerService.updateByPrimaryKeySelective(record);
		ResponseUtil.result(response,JsonUtil.toJsonStr("success"));
	}
	
	@RequestMapping("/addNewCIMRecord")
	@ResponseBody
	public Map<String, Object> addNewRecord(ConsultInfoManage record){
		
		Map<String, Object> map = new HashMap<>();
		
		SysUser sy = (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
		SysDepartment sd = sysDepartmentService.selectByPrimaryKey(sy.getCompanyId());
		if(sd.getType()==3){
			record.setDepartmentId1(sy.getCompanyId());
			record.setDepartmentName1(sd.getFullName());
			record.setDepartmentId2(sy.getCompanyId());
			record.setDepartmentName2(sd.getFullName());
		}else{
			record.setDepartmentId2(sy.getDepartmentId());
			record.setDepartmentName2(sy.getDeptName());
		}
		record.setCounselorId(sy.getUserId());
		record.setCounselor(sy.getRealName());
		record.setStatus(new Byte("2"));
		consultInfoManageService.insert(record);
		
		map.put("status", "success");
		map.put("msg", "新增成功！");
		
		return map;
	}
	
	/**
	 * 
	 * @Description : 获取统计信息，用户id+日期标识作为key放入redis 如果不存在存入缓存，如果存在读取回写到response
	 * @author zealot
	 * @param @param record
	 * @param @param response
	 * @return void
	 * @version 创建时间 : 2016年12月16日 上午9:03:17
	 * @thorws
	 */
	@RequestMapping("/ajaxLoadCount")
	public void ajaxLoadCount(CountWorkBench record,HttpServletResponse response,String type){
		SysUser sy = (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
		ICache ic = systemConfigManager.getCacheInCacheServer();
		
		SysDuty sd =  sysDutyService.selectByPrimaryKey(sy.getDutyId());
		
		if(sd!=null){
			if("11".equals(sd.getCode())||"10".equals(sd.getCode())){
				record.setRoleFW("1");
				record.setDepId1(sy.getCompanyId());
			}else if("12".equals(sd.getCode())){
				record.setRoleFW("2");
				record.setDepId1(sy.getDepartmentId());
			}else{
				record.setRoleFW("3");
			}
		}else{
			record.setRoleFW("3");
		}
		record.setUserId(sy.getUserId());
		CountWorkBench cwb = new CountWorkBench();
		if(SessionModel.NOW.equals(type)){
			record = returnCountWorkBench(record,SessionModel.NOW);
			if(ic.containsKey(SessionModel.SCPOE, sy.getUserId()+SessionModel.NOW)){
				cwb = JsonUtil.readValue(ic.get(SessionModel.SCPOE, sy.getUserId()+SessionModel.NOW),CountWorkBench.class);
			}else{
				cwb = consultInfoManageService.localCount(record);
				if(cwb!=null)
				ic.put(SessionModel.SCPOE,sy.getUserId()+SessionModel.NOW,cwb,SessionModel.EXPIRED1);
			}
		}
		if(SessionModel.WEEK.equals(type)){
			record = returnCountWorkBench(record,SessionModel.WEEK);
			if(ic.containsKey(SessionModel.SCPOE, sy.getUserId()+SessionModel.WEEK)){
				cwb = JsonUtil.readValue(ic.get(SessionModel.SCPOE, sy.getUserId()+SessionModel.WEEK),CountWorkBench.class);
			}else{
				cwb = consultInfoManageService.localCount(record);
				if(cwb!=null)
				ic.put(SessionModel.SCPOE,sy.getUserId()+SessionModel.WEEK,cwb,SessionModel.EXPIRED1);
			}
		}
		if(SessionModel.MONTH.equals(type)){
			record = returnCountWorkBench(record,SessionModel.MONTH);
			if(ic.containsKey(SessionModel.SCPOE, sy.getUserId()+SessionModel.MONTH)){
				cwb = JsonUtil.readValue(ic.get(SessionModel.SCPOE, sy.getUserId()+SessionModel.MONTH),CountWorkBench.class);
			}else{
				cwb = consultInfoManageService.localCount(record);
				if(cwb!=null)
				ic.put(SessionModel.SCPOE,sy.getUserId()+SessionModel.MONTH,cwb,SessionModel.EXPIRED1);
			}
		}
		if(SessionModel.QUARTER.equals(type)){
			record = returnCountWorkBench(record,SessionModel.QUARTER);
			if(ic.containsKey(SessionModel.SCPOE, sy.getUserId()+SessionModel.QUARTER)){
				cwb = JsonUtil.readValue(ic.get(SessionModel.SCPOE, sy.getUserId()+SessionModel.QUARTER),CountWorkBench.class);
			}else{
				cwb = consultInfoManageService.localCount(record);
				if(cwb!=null)
				ic.put(SessionModel.SCPOE,sy.getUserId()+SessionModel.QUARTER,cwb,SessionModel.EXPIRED1);
			}
		}
		if(SessionModel.YEAR.equals(type)){
			record = returnCountWorkBench(record,SessionModel.YEAR);
			if(ic.containsKey(SessionModel.SCPOE, sy.getUserId()+SessionModel.YEAR)){
				cwb = JsonUtil.readValue(ic.get(SessionModel.SCPOE, sy.getUserId()+SessionModel.YEAR),CountWorkBench.class);
			}else{
				cwb = consultInfoManageService.localCount(record);
				if(cwb!=null)
				ic.put(SessionModel.SCPOE,sy.getUserId()+SessionModel.YEAR,cwb,SessionModel.EXPIRED1);
			}
		}
		if(SessionModel.SUM.equals(type)){
			record = returnCountWorkBench(record,SessionModel.SUM);
			if(ic.containsKey(SessionModel.SCPOE, sy.getUserId()+SessionModel.SUM)){
				cwb = JsonUtil.readValue(ic.get(SessionModel.SCPOE, sy.getUserId()+SessionModel.SUM),CountWorkBench.class);
			}else{
				cwb = consultInfoManageService.localCount(record);
				if(cwb!=null)
				ic.put(SessionModel.SCPOE,sy.getUserId()+SessionModel.SUM,cwb,SessionModel.EXPIRED1);
			}
		}
		
		ResponseUtil.result(response, JsonUtil.toJsonStr(cwb));
	}
	
	
	private static CountWorkBench returnCountWorkBench(CountWorkBench record,String type){
		if(SessionModel.NOW.equals(type)){
			record.setBeginTime("2016-12-12");
			record.setEndTime("2016-12-16");
		}
		if(SessionModel.WEEK.equals(type)){
			record.setBeginTime(DataUtil.getWeekStartDate().toString());
			record.setEndTime(DataUtil.getNow());
		}
		if(SessionModel.MONTH.equals(type)){
			record.setBeginTime(DataUtil.getMonthStartDate().toString());
			record.setEndTime(DataUtil.getNow());
		}
		if(SessionModel.QUARTER.equals(type)){
			record.setBeginTime(DataUtil.getCurrentQuarterStartTime().toString());
			record.setEndTime(DataUtil.getNow());
		}
		if(SessionModel.YEAR.equals(type)){
			record.setBeginTime(DataUtil.getYearStartDate().toString());
			record.setEndTime(DataUtil.getNow());
		}
		if(SessionModel.SUM.equals(type)){
			record.setBeginTime(null);
			record.setEndTime(null);
		}
		return record;
	}
	
	/**
	 * 
	 * @Description : 短信发送
	 * @author zealot
	 * @param @param msg
	 * @param @return
	 * @return Map<String,Object>
	 * @version 创建时间 : 2016年12月22日 上午10:57:35
	 * @thorws
	 */
	@RequestMapping("/sendMsg")
	@ResponseBody
	public Map<String, Object> sendMsg(Msg msg){
		Map<String, Object> map = new HashMap<>();
		try {
			map.put("status", "success");
			map.put("msg", SMSUtil.sendSms(msg.getMoblie(), msg.getMsg()));
		} catch (IOException e) {
			map.put("status", "error");
			map.put("msg", "发送失败！");
		}
		return map;
	}
	
	/**
	 * 
	 * @Description : 组内排名
	 * @author zealot
	 * @param @param record
	 * @param @param response
	 * @param @param type
	 * @return void
	 * @version 创建时间 : 2017年1月9日 上午10:24:18
	 * @thorws
	 */
	@RequestMapping("/ajaxLoadGroup")
	public void ajaxLoadGroup(CountWorkBench record,HttpServletResponse response,String type){
		SysUser sy = (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
		record.setUserId(sy.getUserId());
		if(sy.getDepartmentId()!=null){
			record.setDepId2(sy.getDepartmentId());
			record.setUserId(sy.getUserId());
			ResponseUtil.result(response, JsonUtil.toJsonStr(consultInfoManageService.localGroup(record)));
		}
	}
	
	/**
	 * 
	 * @Description : 总业绩
	 * @author zealot
	 * @param @param record
	 * @param @param response
	 * @param @param type
	 * @return void
	 * @version 创建时间 : 2017年1月9日 上午10:24:36
	 * @thorws
	 */
	@RequestMapping("/ajaxLoadSum")
	public void ajaxLoadSum(CountWorkBench record,HttpServletResponse response,String type){ 
		SysUser sy = (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
		if("06".equals(sy.getDyCode())){
			record.setRoleFW("3");
			record.setUserId(sy.getUserId());
			ResponseUtil.result(response, JsonUtil.toJsonStr(consultInfoManageService.localSum(record)));
		}else{
				if("1".equals(sy.getDepType())){
					List<SysUser> userList = getUsers();
					String ar = "";
					for(SysUser e:userList){
						ar = ar+"'"+e.getUserId()+"',";
					}
					ar = ar+"'"+sy.getUserId()+"'";
					record.setRoleFW("4");
					record.setUserId(ar);
					ResponseUtil.result(response, JsonUtil.toJsonStr(consultInfoManageService.localSum(record)));
				}else if("3".equals(sy.getDepType())){{
					if(sy.getDepartmentId()==null){
						record.setRoleFW("1");
						record.setDepId1(sy.getCompanyId());
					}else{
						record.setRoleFW("2");
						record.setDepId1(sy.getDepartmentId());
					}
					ResponseUtil.result(response, JsonUtil.toJsonStr(consultInfoManageService.localSum(record)));
				}
			}
		}
		
	}
	
	/**
	 * 
	 * @Description : 总排名
	 * @author zealot
	 * @param @param record
	 * @param @param response
	 * @param @param type
	 * @return void
	 * @version 创建时间 : 2017年1月9日 上午10:24:51
	 * @thorws
	 */
	@RequestMapping("/ajaxSumSort")
	public void ajaxSumSort(CountWorkBench record,HttpServletResponse response,String type){ 
		SysUser sy = (SysUser)SessionUtils.get(SessionModel.SESSION_USER);
		if("06".equals(sy.getDyCode())){
			record.setRoleFW("3");
			record.setUserId(sy.getUserId());
			ResponseUtil.result(response, JsonUtil.toJsonStr(consultInfoManageService.localSumSort(record)));
		}else{
				if("1".equals(sy.getDepType())){
					
				}else if("3".equals(sy.getDepType())){{
					if(sy.getDepartmentId()==null){
						record.setRoleFW("1");
						record.setDepId1(sy.getCompanyId());
					}else{
						record.setRoleFW("2");
						record.setDepId1(sy.getDepartmentId());
					}
					ResponseUtil.result(response, JsonUtil.toJsonStr(consultInfoManageService.localSumSort(record)));
				}
			}
		}
		
	}
	
	/**
	 * 
	 * @Description : 获取欠费记录
	 * @author zealot
	 * @param @param response
	 * @param @param request
	 * @param @param t
	 * @return void
	 * @version 创建时间 : 2017年1月11日 上午9:31:35
	 * @thorws
	 */
	@RequestMapping("/ajaxBeforePay")
	public void ajaxBeforePay(HttpServletResponse response,HttpServletRequest request,ConsultInfoManagePay t){
		ResponseUtil.result(response, JsonUtil.toJsonStr(consultInfoManagePayService.selectByUs(t)));
	}
	
}
